package great.easychat.help;

import androidx.lifecycle.Observer;
import android.content.Context;
import androidx.annotation.Nullable;

import com.pince.frame.mvvm.FinalVMFragment;
import com.pince.frame.mvvm.architecture.BaseViewModel;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import great.easychat.help.dialog.LoadDialog;
import great.easychat.help.util.ToastUtil;

/**
 * @date 2017/7/10
 */

public abstract class BaseFragment<M extends BaseViewModel> extends FinalVMFragment<M> {

    protected Context mContext;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    protected void onFragmentCreateStart() {
        super.onFragmentCreateStart();
        if (viewModel != null) {
            viewModel.getShowToastLiveData().observe(this, new Observer<String>() {
                @Override
                public void onChanged(@Nullable String msg) {
                    ToastUtil.show(msg);
                }
            });
            viewModel.getShowLoadingLiveData().observe(this, new Observer<Boolean>() {
                @Override
                public void onChanged(@Nullable Boolean aBoolean) {
                    if (aBoolean) {
                        showLoadDialog(null);
                    } else {
                        hideLoadDialog();
                    }
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(mContext);
    }

    @Override
    public void onPause() {
        MobclickAgent.onPause(mContext);
        MobclickAgent.onPause(mContext);
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        hideLoadDialog();
    }

    private LoadDialog loadDialog = null;

    protected void showLoadDialog(@Nullable String title) {
        if (loadDialog == null) {
            loadDialog = new LoadDialog(getActivity());
        }
        loadDialog.showOnce(title);
    }

    protected void hideLoadDialog() {
        if (loadDialog != null && loadDialog.isShowing()) {
            loadDialog.dismiss();
        }
    }

    /**
     * 注册eventbus
     */
    protected void registEventBus(Object object) {
        if (!EventBus.getDefault().isRegistered(object)) {
            EventBus.getDefault().register(object);
        }
    }

    /**
     * 取消注册eventbus
     */
    protected void unregisterEventBus(Object object) {
        if (EventBus.getDefault().isRegistered(object)) {
            EventBus.getDefault().unregister(object);
        }
    }

}